/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.baumi.tankwars.util;

/**
 *
 * @author Michael Baumgartner
 */
public class Line2d {

    private double x1;
    private double x2;
    private double y1;
    private double y2;

    public Line2d(double x1, double x2, double y1, double y2) {
        this.x1 = x1;
        this.x2 = x2;
        this.y1 = y1;
        this.y2 = y2;
    }

    public double getX1() {
        return x1;
    }

    public void setX1(double x1) {
        this.x1 = x1;
    }

    public double getX2() {
        return x2;
    }

    public void setX2(double x2) {
        this.x2 = x2;
    }

    public double getY1() {
        return y1;
    }

    public void setY1(double y1) {
        this.y1 = y1;
    }

    public double getY2() {
        return y2;
    }

    public void setY2(double y2) {
        this.y2 = y2;
    }

    public boolean intersectsLine(Line2d m) {

        //Punkte der erste Geraden
        double x1 = this.x1;
        double y1 = this.y1;
        double x2 = this.x2;
        double y2 = this.y2;

        //Punkte der zweiten Geraden
        double x3 = m.getX1();
        double y3 = m.getY1();
        double x4 = m.getX2();
        double y4 = m.getY2();

        // Zaehler
        double zx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4);
        double zy = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4);

        // Nenner
        double n = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);

        //Geraden sind Paralell
        if ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) == 0) {
            return false;
        }
        double SchnittX = zx / n;
        double SchnittY = zy / n;

        if ((SchnittX - x1) / (x2 - x1) > 1 || (SchnittX - x2) / (x1 - x2) > 1 && ((SchnittY - y1) / (y2 - y1) > 1 || (SchnittY - y2) / (y1 - y2) > 1)) {
            return false;
        }

        if ((SchnittX - x3) / (x4 - x3) > 1 || (SchnittX - x4) / (x3 - x4) > 1 && ((SchnittY - y3) / (y4 - y3) > 1 || (SchnittY - y4) / (y3 - y4) > 1)) {
            return false;
        }
        return true;
    }

}
